from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import logout
from django.contrib.auth import authenticate, login
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from ProyectoAnimeToones.app.models import *
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.template import Context, Template
import datetime

def index(request):
    animes_lista = Anime.objects.all().order_by('-ranking') [:1]
    return render_to_response('index.html', {'animes_lista': animes_lista}, context_instance=RequestContext(request))

@login_required(login_url='/')
def topten(request):
    animes_lista = Anime.objects.all().order_by('-ranking') [:5]
    return render_to_response('topten.html', {'animes_lista': animes_lista}, context_instance=RequestContext(request))

@login_required(login_url='/')
def agregarlink(request, id=None):
    if id:
        auto = get_object_or_404(Anime, pk=id)
    else:
        auto = Anime()
    if request.method == 'POST': # If the form has been submitted...
        form = AnimeForm(request.POST, instance=auto) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            # ...
            auto.ranking = auto.establecerRanking()
            auto.seccion_anime = request.user
            auto = form.save()
            return HttpResponseRedirect("/todosanime/")  # Redirect after POST
    else:
        form = AnimeForm(instance=auto) # An unbound form

    return render_to_response('agregarlink.html', {
        'form': form,
    }, context_instance=RequestContext(request))
    
@login_required(login_url='/')
def todosanime(request):
    animes_lista = Anime.objects.all().order_by('-ranking')
    return render_to_response('todosanime.html', {'animes_lista': animes_lista}, context_instance=RequestContext(request))
    
@login_required(login_url='/')  
def detail(request, anime_nombre):
    p = get_object_or_404(Anime, nombre=anime_nombre)
    return render_to_response('detail.html', {'anime': p}, context_instance=RequestContext(request))

@login_required(login_url='/')
def logout_view(request):
    logout(request)
    return HttpResponseRedirect('/')

@csrf_exempt
def loguear(request):
    if request.method == "POST":
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                return topten(request)
            # Redirect to a success page.
            else:
                return HttpResponseRedirect ('/topten/')
        else:
            return HttpResponseRedirect('/error/')
    else:
        return HttpResponseRedirect('/error/')
    
@login_required(login_url='/')
def votar(request, anime_id):
    enc = get_object_or_404(Anime, pk=anime_id)
    enc.votar()
    enc.save()
    return HttpResponseRedirect('/todosanime/')

@login_required(login_url='/')
def search(request):
    if 'q' in request.GET and request.GET['q']:
        q = request.GET['q']
        animes_lista = Anime.objects.filter(nombre__icontains=q)
        return render_to_response('todosanime.html', {'animes_lista': animes_lista, 'query': q}, context_instance=RequestContext(request))
    else:
        return render_to_response('todosanime.html', {'error': True}, context_instance=RequestContext(request))

@login_required(login_url='/')
def bad_search(request):
    message = 'You searched for: %r' % request.GET['q']
    return HttpResponse(message)

def errorLogin(request):
    return render_to_response('login.html', context_instance=RequestContext(request))
    
